import { App, Cascader, Form, Input, Modal, Select } from "antd"
import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from "react";
import TextArea from "antd/es/input/TextArea";
import useFindData from "@/hooks/useFindData";
import { addWorkplacesDataApi, updateWorkplacesDataApi, type WorkplaceType } from "@/api/workplace";
import type { OrganizationTypeItem } from "@/api/organization";

// 定义子组件暴露给父组件的数据的类型
export interface WorkplaceRef {
    onOpenForm: (item?: WorkplaceType) => void
}


const WorkplaceForm = (props: any, ref: any) => {
    const { getWorkplaces } = props
    const [open, setOpen] = useState(false);
    const [form] = Form.useForm();
    const { getCountriesHook, countriesData, getCitiesHook, citiesData, getOrganizationTypesHook, organizationTypesData } = useFindData();
    const [formData, setFormData] = useState({ _id: '' });
    const { message } = App.useApp();
    useEffect(() => {
        if (open) {
            getCountriesHook();
            getOrganizationTypesHook();
        }
    }, [open])
    useEffect(() => {
        if (!open) {
            setFormData({ _id: '' });
            form.resetFields();
        }
    }, [open])
    const modalTitle = useMemo(() => {
        return formData._id ? '编辑工作地点' : '新增工作地点'
    }, [formData]);


    //弹窗确认 新增/修改数据
    const onOK = async () => {
        form.submit();
    }

    const onFormFinish = async (values: any) => {
        if (formData._id) {
            const res = await updateWorkplacesDataApi({
                ...formData,
                ...values
            });
            if (res.code == 200) {
                message.success('修改成功')
                setOpen(false);
                getWorkplaces();
            } else {
                message.error(res.message)
            }
        } else {
            const res = await addWorkplacesDataApi(values);
            if (res.code == 200) {
                message.success('新增成功')
                setOpen(false);
                getWorkplaces();
            } else {
                message.error(res.message)
            }
        }

    }
    //弹窗关闭
    const onCancel = () => {
        setOpen(false);
        getWorkplaces();
    }
    //打开弹窗 
    const onOpenForm = (data?: WorkplaceType) => {
        setOpen(true);
        if (data) {
            setFormData(data);
            form.setFieldsValue({
                ...data,
                organizationTypeId: (data.organizationTypeId as OrganizationTypeItem)._id
            });
        }
    }
    // 暴露内容给父组件
    useImperativeHandle(ref, () => {
        return {
            onOpenForm,
        }
    })
    //切换国家后
    const onChangeCountry = (value: string) => {
        form.resetFields(['city']);
        getCitiesHook(value);
    }
    return (
        <>
            <Modal
                title={modalTitle}
                open={open}
                onOk={onOK}
                onCancel={onCancel}
                forceRender={true}
            >
                <Form
                    form={form}
                    name="workplaceForm"
                    labelCol={{ style: { width: 80 } }}
                    style={{ marginBottom: 20 }}
                    onFinish={onFormFinish}
                >
                    <Form.Item name="name" label="工作地点" rules={[{ required: true, message: '工作地点不能为空' }]} >
                        <Input placeholder="请输入"></Input>
                    </Form.Item>
                    <Form.Item name="country" label="国家/地区" rules={[{ required: true, message: '国家/地区不能为空' }]}>
                        <Select options={countriesData} fieldNames={{ label: "name", value: 'name', }}
                            onChange={onChangeCountry} placeholder="请选择"></Select>
                    </Form.Item>
                    <Form.Item name="city" label="所在城市" rules={[{ required: true, message: '所在城市不能为空' }]}>
                        <Cascader options={citiesData} fieldNames={{
                            label: "name", value: 'name',
                            children: 'response_data'
                        }} placeholder="请选择" ></Cascader>
                    </Form.Item>
                    <Form.Item name="address" label="详细地址" >
                        <Input placeholder="请输入"></Input>
                    </Form.Item>
                    <Form.Item name="organizationTypeId" label="类型" >
                        <Select options={organizationTypesData.rows} fieldNames={{ label: "name", value: '_id', }}
                            placeholder="请选择"></Select>
                    </Form.Item>
                    <Form.Item name="postcode" label="邮政编码" >
                        <Input placeholder="请输入"></Input>
                    </Form.Item>
                    <Form.Item name="desc" label="描述" >
                        <TextArea rows={4} />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}

export default forwardRef(WorkplaceForm)